package org.hospital.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.SimpleFormatter;

import org.hospital.entity.Clinic;
import org.hospital.entity.ClinicDAO;
import org.hospital.entity.Department;
import org.hospital.entity.DepartmentDAO;
import org.hospital.entity.Employee;
import org.hospital.entity.EmployeeDAO;
import org.hospital.entity.Permission;
import org.hospital.entity.PermissionDAO;
import org.hospital.entity.Position;
import org.hospital.entity.PositionDAO;
import org.hospital.entity.PositionPermission;
import org.hospital.entity.PositionPermissionDAO;
import org.hospital.entity.PositionPermissionId;
import org.hospital.service.PermissionService;
import org.hospital.util.Constant;
import org.hospital.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Service
public class PermissionServiceImpl implements PermissionService {

	@Autowired
	private PositionDAO psDao;
	@Autowired
	private PermissionDAO pmDao;
	@Autowired
	private PositionPermissionDAO ppDao;
	@Autowired
	private EmployeeDAO eDao;
	@Autowired
	private ClinicDAO cDao;
	@Autowired
	private DepartmentDAO dpmDao;

	@Override
	public Position getPositionByid(int positionId) {
		return psDao.findById(positionId);
	}

	@Override
	public List<Permission> getPermissionByName(String name) {
		return pmDao.findByName(name);
	}

	@Override
	public List<Permission> getPermissionByPosition(int positionId) {

		List<Permission> pmList = new ArrayList<Permission>();
		List<PositionPermission> ppList = ppDao.findByProperty("id.positionId", positionId);
		for (Iterator iterator = ppList.iterator(); iterator.hasNext();) {
			PositionPermission pp = (PositionPermission) iterator.next();
			pmList.add(pmDao.findById(pp.getId().getPermissionId()));
		}

		return pmList;
	}

	@Override
	public Boolean isPermisionEnough(int positionId, String permissionName, int rank) {
		// 判断职位等级
		Position position = psDao.findById(positionId);
		if (position.getRank() < rank) {
			return false;
		}

		List<Permission> pmList = pmDao.findByProperty(pmDao.NAME, permissionName);
		if (pmList.size() <= 0) {
			return false;
		}
		// 判断是否具有指定权限
		PositionPermission pp = ppDao.findById(new PositionPermissionId(positionId, pmList.get(0)
				.getPermissionId()));

		if (pp == null) {
			return false;
		}
		return true;
	}

	@Override
	public Boolean createPosition(Position ps, JSONArray permissionIds) {

		ps = psDao.merge(ps);

		for (int i = 0; i < permissionIds.size(); i++) {
			int permissionId = permissionIds.getInteger(i);
			PositionPermission pp = new PositionPermission();
			pp.setId(new PositionPermissionId(ps.getPositionId(), permissionId));
			ppDao.merge(pp);
		}

		return true;
	}

	@Override
	public JSONArray getAllPosition() {
		JSONArray resultJA = new JSONArray();
		List<Position> psList = psDao.findAll();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		for (int i = 0; i < psList.size(); i++) {
			Position ps = psList.get(i);
			JSONObject resultJO = new JSONObject();

			// 获取职位的权限
			List<Permission> pmList = getPermissionByPosition(ps.getPositionId());
			JSONArray pmJA = new JSONArray();
			for (int j = 0; j < pmList.size(); j++) {
				Permission pm = pmList.get(j);
				pmJA.add(pm.getPermissionId());
			}

			Employee creator = eDao.findById(ps.getCreatorId());
			resultJO.put("positionId", ps.getPositionId());
			resultJO.put("positionName", ps.getName());
			resultJO.put("description", ps.getDescription());
			resultJO.put("creatorId", ps.getCreatorId());
			resultJO.put("creatorName", creator.getName());
			resultJO.put("createTime", sdf.format(ps.getCreateTime()));
			resultJO.put("rankString", StringUtil.rankToString(ps.getRank()));
			resultJO.put("rankInt", ps.getRank());
			resultJO.put("permission", pmJA);
			resultJA.add(resultJO);
		}

		return resultJA;
	}

	@Override
	public Boolean alterPosition(Position ps, JSONArray permissionIds) {
		System.out.println("alterPosition.dbPosition : " + JSON.toJSONString(ps, true));
		Position dbPosition = psDao.findById(ps.getPositionId());
		// 设置修改的属性
		dbPosition.setName(ps.getName());
		dbPosition.setRank(ps.getRank());
		dbPosition.setDescription(ps.getDescription());
		// System.out.println("alterPosition.rank : "+ps.getRank());
		// 插入数据库
		dbPosition = psDao.merge(dbPosition);
		if (dbPosition == null) {
			return false;
		}
		// 删除职位权限表信息
		List<PositionPermission> ppList = ppDao.findByProperty("id.positionId",
				dbPosition.getPositionId());
		ppDao.deleteList(ppList);
		// 插入职位权限表信息
		for (int i = 0; i < permissionIds.size(); i++) {
			int permissionId = permissionIds.getInteger(i);
			PositionPermission pp = new PositionPermission();
			pp.setId(new PositionPermissionId(dbPosition.getPositionId(), permissionId));
			ppDao.merge(pp);
		}
		return true;
	}

	@Override
	public JSONObject getPermissionJO(Employee user) {
		JSONObject resultJO = new JSONObject();
		Position ps = psDao.findById(user.getPositionId());
		List<Department> dpmList = dpmDao.findByClinicId(user.getClinicId());
		List<Clinic> cList = cDao.findAll();
		Clinic userClinic = cDao.findById(user.getClinicId());

		/********************* 操作单据权限 **********************/
		// 创建治疗项目单据
		if (isPermisionEnough(ps.getPositionId(), Constant.CREATE_TREATMENT_BILL.getName(), 1)) {
			resultJO.put("createTreatBill", ps.getRank());
		} else {
			resultJO.put("createTreatBill", 0);
		}
		if (isPermisionEnough(ps.getPositionId(), Constant.CREATE_TREATMENT_BILL_PERSON.getName(),
				1)) {
			resultJO.put("createTreatBillPerson", ps.getRank());
		} else {
			resultJO.put("createTreatBillPerson", 0);
		}
		// 查看治疗项目单据
		// 1:查看自身开的治疗单据;2:查看部门下所有治疗单据信息;3、4:查看门诊下所有治疗单据信息;5:查看所有治疗单据信息;
		if (isPermisionEnough(ps.getPositionId(), Constant.QUERY_TREATMENT_BILL.getName(), 1)) {
			resultJO.put("queryTreatBill", ps.getRank());
		} else {
			resultJO.put("queryTreatBill", 0);
		}
		// 创建费用项目单据
		if (isPermisionEnough(ps.getPositionId(), Constant.CREATE_FUND_BILL.getName(), 1)) {
			resultJO.put("createFundBill", ps.getRank());
		} else {
			resultJO.put("createFundBill", 0);
		}
		// 查看费用项目单据
		// 1:查看自身开的费用单据;2:查看部门下所有费用单据信息;3、4:查看门诊下所有费用单据信息;5:查看所有费用单据信息;
		if (isPermisionEnough(ps.getPositionId(), Constant.QUERY_FUND_BILL.getName(), 1)) {
			resultJO.put("queryFundBill", ps.getRank());
		} else {
			resultJO.put("queryFundBill", 0);
		}

		/********************* 操作员工权限 **********************/
		// 创建员工 只有管理员可以
		if (isPermisionEnough(ps.getPositionId(), Constant.CREATE_EMPLOYEE.getName(), 5)) {
			resultJO.put("createEmployee", ps.getRank());
		} else {
			resultJO.put("createEmployee", 0);
		}
		// 修改员工信息(包括修改职位、所属科室) 普通用户只能修改自身基本信息(前端实现)
		if (isPermisionEnough(ps.getPositionId(), Constant.ALTER_EMPLOYEE.getName(), 5)) {
			resultJO.put("alterEmployee", ps.getRank());
		} else {
			resultJO.put("alterEmployee", 0);
		}

		/********************* 操作门诊权限 **********************/
		// 创建门诊
		if (isPermisionEnough(ps.getPositionId(), Constant.CREATE_CLINIC.getName(), 5)) {
			resultJO.put("createClinic", ps.getRank());
		} else {
			resultJO.put("createClinic", 0);
		}
		// 修改门诊信息 3、4:是该门诊负责人;5:具有创建权限;
		// 管理员才可以修改门诊负责人

		resultJO.put("alterClinic", 0);
		for (int i = 0; i < cList.size(); i++) {
			Clinic clinic = cList.get(i);
			if (clinic.getEmployeeId().equals(user.getEmployeeId())) {
				resultJO.put("alterClinic", ps.getRank());
				break;
			}
		}
		if (isPermisionEnough(ps.getPositionId(), Constant.CREATE_CLINIC.getName(), 5)) {
			resultJO.put("alterClinic", ps.getRank());
		}

		/********************* 操作科室权限 **********************/
		// 创建科室
		if (isPermisionEnough(ps.getPositionId(), Constant.CREATE_DEPARTMENT.getName(), 5)) {
			resultJO.put("createDepartment", ps.getRank());
		} else {
			resultJO.put("createDepartment", 0);
		}
		// 修改科室信息 2、3、4:是该科室负责人;3、4:是该门诊负责人;5：具有创建权限;
		// 修改科室负责人 3、4:是该门诊负责人;5:具有创建权限;
		// 3:管理员;2:门诊负责人;1:科室负责人;0:不具有权限;
		resultJO.put("alterDepartment", 0); // 默认为0
		for (int i = 0; i < dpmList.size(); i++) { // 如果为科室负责人则为1
			Department dpm = dpmList.get(i);
			if (dpm.getEmployeeId().equals(user.getEmployeeId())) {
				resultJO.put("alterDepartment", 1);
				break;
			}
		}
		if (userClinic.getEmployeeId().equals(user.getEmployeeId())) {
			resultJO.put("alterDepartment", 2);
		}
		// 如果为管理员则为3
		if (isPermisionEnough(ps.getPositionId(), Constant.CREATE_DEPARTMENT.getName(), 5)) {
			resultJO.put("alterDepartment", 3);
		}

		/********************* 操作项目权限 **********************/
		// 创建项目(包括治疗、费用):只有管理员可以
		if (isPermisionEnough(ps.getPositionId(), Constant.CREATE_PROJECT.getName(), 5)) {
			resultJO.put("createProject", ps.getRank());
		} else {
			resultJO.put("createProject", 0);
		}
		// 修改项目(包括治疗、费用):只有管理员可以
		if (isPermisionEnough(ps.getPositionId(), Constant.ALTER_PROJECT.getName(), 5)) {
			resultJO.put("alterProject", ps.getRank());
		} else {
			resultJO.put("alterProject", 0);
		}

		/********************* 操作客户权限 **********************/
		// 查看用户包括治疗项目信息
		if (isPermisionEnough(ps.getPositionId(), Constant.QUERY_CLIENT.getName(), 1)) {
			resultJO.put("queryClient", ps.getRank());
		} else {
			resultJO.put("queryClient", 0);
		}
		// 创建用户
		if (isPermisionEnough(ps.getPositionId(), Constant.CREATE_CLIENT.getName(), 1)) {
			resultJO.put("createClient", ps.getRank());
		} else {
			resultJO.put("createClient", 0);
		}
		// 修改用户
		if (isPermisionEnough(ps.getPositionId(), Constant.ALTER_CLIENT.getName(), 1)) {
			resultJO.put("alterClient", ps.getRank());
		} else {
			resultJO.put("alterClient", 0);
		}

		/********************* 操作病例权限 **********************/
		// 查看病例
		if (isPermisionEnough(ps.getPositionId(), Constant.QUERY_RECORD.getName(), 1)) {
			resultJO.put("queryRecord", ps.getRank());
		} else {
			resultJO.put("queryRecord", 0);
		}
		// 创建病例
		if (isPermisionEnough(ps.getPositionId(), Constant.CREATE_RECORD.getName(), 1)) {
			resultJO.put("createRecord", ps.getRank());
		} else {
			resultJO.put("createRecord", 0);
		}
		// 修改病例
		if (isPermisionEnough(ps.getPositionId(), Constant.ALTER_RECORD.getName(), 1)) {
			resultJO.put("alterRecord", ps.getRank());
		} else {
			resultJO.put("alterRecord", 0);
		}

		/********************* 操作职位权限 **********************/
		// 创建职位
		if (isPermisionEnough(ps.getPositionId(), Constant.CREATE_POSITION.getName(), 5)) {
			resultJO.put("createPosition", ps.getRank());
		} else {
			resultJO.put("createPosition", 0);
		}
		// 修改职位
		if (isPermisionEnough(ps.getPositionId(), Constant.ALTER_POSITION.getName(), 5)) {
			resultJO.put("alterPosition", ps.getRank());
		} else {
			resultJO.put("alterPosition", 0);
		}

		/********************* 查看报表权限 **********************/
		// 查看报表
		if (isPermisionEnough(ps.getPositionId(), Constant.GET_REPORT.getName(), 2)) {
			resultJO.put("getReport", ps.getRank());
		} else {
			resultJO.put("getReport", 0);
		}

		return resultJO;
	}

	@Override
	public JSONArray getPermissionByPositionId(int positionId) {
		JSONArray resultJA = new JSONArray();
		List<PositionPermission> ppList = ppDao.findByProperty("id.positionId", positionId);
		for (int i = 0; i < ppList.size(); i++) {
			resultJA.add(ppList.get(i).getId().getPermissionId());
		}
		return resultJA;
	}
}
